package com.xj.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import static ch.qos.logback.core.util.EnvUtil.isWindows;

/**
 * 文件操作工具类
 * @author chao.deng
 * @date 2020/5/12
 */
@Slf4j
public class FileUtils extends org.apache.commons.io.FileUtils implements Serializable {

	/**
	 * 按照文件名称，like查找最新的文件
	 * @param path
	 * @param likeName
	 * @return 文件的绝对路径
	 */
	public static String findFileName(String path,String likeName){
		File fold = new File(path);
		if(!fold.exists()){
			fold.mkdirs();
		}
		List<File> fileList = new ArrayList<>();
		if(fold.isDirectory()){
			File[] files = fold.listFiles();
			for(File f : files){
				if(f.getName().contains(likeName)){
					fileList.add(f);
				}
			}
			fileList.sort(Comparator.comparing(File::lastModified));
			if(!CollectionUtils.isEmpty(fileList)){
				return fileList.get(fileList.size()-1).getAbsolutePath();
			}
		}
		return null;
	}
	/**
	 * 根据路径创建一系列的目录
	 *
	 * @param path
	 */
	public static void mkDirectory(String path) {
		File file;
		try {
			file = new File(path);
			if (!file.exists()) {
				file.mkdirs();
			}
		} catch (RuntimeException e) {
			log.error("",e);
		} finally {
			file = null;
		}
	}

	public static void removeDir(File d) {
		removeDir(d, false);
	}

	private static void removeDir(File d, boolean inShutdown) {
		String[] list = d.list();
		if (list == null) {
			list = new String[0];
		}

		for(int i = 0; i < list.length; ++i) {
			String s = list[i];
			File f = new File(d, s);
			if (f.isDirectory()) {
				removeDir(f, inShutdown);
			} else {
				delete(f, inShutdown);
			}
		}

		delete(d, inShutdown);
	}

	public static File delete(File f) {
	  return 	delete(f, false);
	}

	public static File delete(File f, boolean inShutdown) {
		if (!f.delete()) {
			if (isWindows()) {
				System.gc();
			}

			try {
				Thread.sleep(10L);
			} catch (InterruptedException var3) {
			}

			if (!f.delete() && !inShutdown) {
				f.deleteOnExit();
			}
		}
          return f;
	}

}
